<template>
  <view class="con">
    <image src="@/static/logo.png" />
    <!-- 登录 -->
    <view class="login-form">
      <view class="account">
        <up-input placeholder="请输入手机号" shape="circle" v-model="account" @change="changeAccountValue"></up-input>
      </view>
      <view class="account">
        <up-input placeholder="请输入验证码" shape="circle" v-model="code" @change="changeCodeValue">
          <template #suffix>
            <up-code ref="uCodeRef" @change="codeChange" seconds="60" @end="end" changeText="X秒重新获取"></up-code>
            <up-button @tap="getCode" type="primary" size="mini">{{ tips }}</up-button>
          </template>
        </up-input>
      </view>
    </view>

    <view class="btn-box">
      <up-button shape="circle" type="primary" @tap="login">
        登录
      </up-button>
      <!-- <up-button class="to-idx-btn" shape="circle" @tap="toIndex">
        回到首页
      </up-button> -->
    </view>
  </view>
</template>

<script setup>
import { encrypt } from '@/utils/crypto.js'

/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  // 头部导航标题
  uni.setNavigationBarTitle({
    title: '用户登录'
  })
})

const account = ref('') // 账号
const code = ref('') // 密码
const tips = ref('获取验证码');
const uCodeRef = ref();

/**
 * 输入框的值
 */
const changeAccountValue = (value) => {
  account.value = value;
}
const changeCodeValue = (value) => {
  code.value = value;
}

/**
 * 登录
 */
const login = () => {
  if (!account.value) {
    uni.showToast({
      title: '您还没输手机号',
      icon: 'none',
      duration: 2000,
    })
    return;
  }
  if (!code.value) {
    uni.showToast({
      title: '您还没输验证码',
      icon: 'none',
      duration: 2000,
    })
    return;
  }
  http.request({
    url: `/api/sms/register?phoneNumber=${account.value}&code=${code.value}`,
    method: 'post',
    data: {}
  })
    .then(({ data }) => {
      http.loginSuccess(data, () => {
        uni.showToast({
          title: '登录成功',
          icon: 'none',
          complete: () => {
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/index/index'
              })
            }, 1000)
          }
        })
      })
    })
}

/**
 * 获取验证码
 */
const getCode = () => {
  if (!account.value) {
    uni.$u.toast('请先输入手机号');
    return;
  }
  if (uCodeRef.value.canGetCode) {
    // 模拟向后端请求验证码
    uni.showLoading({
      title: '正在获取验证码',
    });
    uni.hideLoading();
    // 这里此提示会被start()方法中的提示覆盖
    http.request({
      url: `/api/sms/send?phoneNumber=${account.value}`,
      method: 'post',
      data: {}
    }).then(() => {
      uni.$u.toast('验证码已发送');
      // 通知验证码组件内部开始倒计时
      uCodeRef.value.start();
    })
  } else {
    uni.$u.toast('倒计时结束后再发送');
  }
}

const codeChange = (text) => {
  tips.value = text;
};

const end = () => {
  tips.value = '获取验证码';
}

/**
 * 回到首页
 */
const toIndex = () => {
  wx.switchTab({
    url: '/pages/index/index'
  })
}
</script>

<style scoped lang="scss">
@import "./accountLogin.scss";
</style>
